package org.yanghe.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.yanghe.lb.LoadBalancer;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
public class ConsumerController {

    @Value("${spring.application.name}")
    private String currentServiceName; //当前服务名
    @Resource
    RestTemplate restTemplate;
    @Resource
    DiscoveryClient discoveryClient;


    /**
     * 测试接口
     * @param name
     * @return
     */
    @GetMapping("/consumer/hello/{name}")
    public String hello(@PathVariable("name") String name){
        return restTemplate.getForObject("http://cloud-provider/provider/hello/"+name,String.class);
    }

    /**
     * 获取服务列表
     * @return
     */
    @RequestMapping("/consumer/getServices")
    public List<String> getServices(){
        return discoveryClient.getServices();
    }


    //引入 Ribbon 负载
    @Resource
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/consumer/ribbon/{name}")
    public String testRibbon(@PathVariable("name")String name){
        ServiceInstance choose = loadBalancerClient.choose("cloud-provider");//不区分大小写
        System.out.println("getUri:"+choose.getUri());
        System.out.println("getHost:"+choose.getHost());
        System.out.println("getPort:"+choose.getPort());
        System.out.println("getInstanceId:"+choose.getInstanceId());
        System.out.println("getMetadata:"+choose.getMetadata());
        System.out.println("getScheme:"+choose.getScheme());
        System.out.println("getServiceId:"+choose.getServiceId());
        return "ConsumerController";
    }


    @Resource
    LoadBalancer loadBalancer;

    /**
     * 使用自定义的轮询算法
     * @return
     */
    @GetMapping(value = "/consumer/lb")
    public String getLoadBalancerLb(){
        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PROVIDER");
        if(instanceList == null || instanceList.size()<=0){
            return null;
        }
        ServiceInstance instances = loadBalancer.instances(instanceList);
        URI uri = instances.getUri();
        return restTemplate.getForObject(uri+"/provider/hello/自定义轮询",String.class);
    }


}
